<template>
  <el-dialog title="购买服务" :visible.sync="visible" width="1000px" append-to-body :before-close="handleClose">
    <div class="box" v-if="orderType === 'members'">
      <div class="jg-steps"><slot name="steps" /></div>
      <div v-if="active == 0" class="order-box">
        <el-table :data="tableData" height="350" style="width: 100%">
          <el-table-column prop="title" label="订单标题" width="180" />
          <el-table-column prop="vipLevelName" label="会员等级" show-overflow-tooltip />
          <el-table-column prop="vipPeriod" label="续费时长" width="180">
            <template slot-scope="scope">
              {{ scope.row.vipPeriod ? scope.row.vipPeriod : 0 }} 个月
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="服务价格(元)" width="180">
            <template slot-scope="scope">
              ¥ {{ scope.row.amount ? scope.row.amount.toFixed(2) : 0.00 }}
            </template>
          </el-table-column>
        </el-table>
        <div class="payment">
          应付款：
          <span>￥{{payAmount()}}</span>
        </div>
        <div class="btns"><div class="btn" @click="payment(tableData[0], 'members')">立即支付</div></div>
        <div class="agreement">
          <el-checkbox v-model="checked">
            阅读并同意
            <a class="link" href="" target="_blank">《支付服务协议》</a>
          </el-checkbox>
        </div>
      </div>
      <div v-if="active == 1" class="payment-box">
        <div class="h">订单提交成功，请尽快付款！</div>
        <div class="em">请您在24小时内完成支付，否则订单会被自动取消</div>
        <div class="price">
          应付款：
          <span>￥{{ payAmount() }}</span>
        </div>
        <div class="pay-tab">
          <div class="tab">
            <div class="box" :class="tabActive == 1 ? 'active' : ''" @click="tabClick(1)">
              <i class="iconfont zgyf-icon-wechat-pay-fill" />
              微信支付
            </div>
            <div class="box" :class="tabActive == 2 ? 'active' : ''" @click="tabClick(2)">
              <i class="iconfont iconfont zgyf-icon-alipay-fill" />
              对公支付
            </div>
          </div>
          <div v-if="tabActive == 1" class="QRCode-box" >
            <div class="QRCode" ref="QRCode"></div>
          </div>
          <div v-if="tabActive == 2" class="company-pay">
            <div class="step1">
              <div class="h">第一步：对公汇款</div>
              <div v-if="companyData" class="em" id="copyText">
                <div class="box">账户名称：{{companyData.bankAccountName}}</div>
                <div class="box">开户银行：{{companyData.bankName}}</div>
                <div class="box">银行账号：{{companyData.bankAccount}}</div>
                <div class="box">汇款金额：¥{{payAmount()}}</div>
                <div class="box">汇款备注：订单号{{tableData.length > 0 ? tableData[0].encode : this.rowData.encode}}</div>
                <div class="box tips">请在对公汇款时务必备注订单号</div>
              </div>
              <div class="btns"><el-button data-clipboard-target="#copyText" class="copyBtn" type="primary" plain @click="copy">一键复制</el-button></div>
            </div>
            <div class="step2">
              <div class="h">第二步：支付完成确认</div>
              <div class="em">
                <div class="box"><span class="tips">转账完成后请点击页面中的「已完成支付」</span>，我们在收到汇款24小时内会为您进行续费（周末、法定假日可能有延时）</div>
              </div>
              <div class="btns"><el-button type="primary" plain @click="successPay()">已完成支付</el-button></div>
              <div class="footer">
                <div class="box">如需加急操作，请在汇款完成后联系【协会客服电话】</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="active == 2" class="success-box">
        <div class="icon"><i class="iconfont zgyf-icon-yiwancheng" /></div>
        <div class="h">订购成功</div>
        <div class="em">{{tabActive == 2 ?'请等待，协会确认到账' : '已自动续期，到期时间为：【'+jnpf.toDate(renewal.expireTime)+'】' }} </div>
        <div class="btns">
          <div class="btn" @click="goToLink('/vip/order/vipOrderRecord')">查看订单</div>
        </div>
      </div>
    </div>
    <div class="box" v-if="orderType === 'service'">
      <div class="jg-steps"><slot name="steps" /></div>
      <div v-if="active == 0" class="order-box">
        <el-table :data="tableData" height="350" style="width: 100%">
          <el-table-column prop="title" label="订单标题" width="180" />
          <el-table-column prop="vipLevelName" label="会员等级" show-overflow-tooltip />
          <el-table-column prop="vipPeriod" label="续费时长" width="180">
            <template slot-scope="scope">
              {{ scope.row && scope.row.vipPeriod ? scope.row.vipPeriod : 0 }} 个月
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="服务价格(元)" width="180">
            <template slot-scope="scope">
              ¥ {{ scope.row.amount ? scope.row.amount.toFixed(2) : 0.00 }}
            </template>
          </el-table-column>
        </el-table>
        <div class="payment">
          应付款：
          <span>￥{{payAmount()}}</span>
        </div>
        <div class="btns"><div class="btn" @click="payment(tableData[0], 'service')">立即支付</div></div>
        <div class="agreement">
          <el-checkbox v-model="checked">
            阅读并同意
            <a class="link" href="" target="_blank">《支付服务协议》</a>
          </el-checkbox>
        </div>
      </div>
      <div v-if="active == 1" class="payment-box">
        <div class="h">订单提交成功，请尽快付款！</div>
        <div class="em">请您在24小时内完成支付，否则订单会被自动取消</div>
        <div class="price">
          应付款：
          <span>￥{{ payAmount() }}</span>
        </div>
        <div class="pay-tab">
          <div class="tab">
            <div class="box" :class="tabActive == 1 ? 'active' : ''" @click="tabClick(1)">
              <i class="iconfont zgyf-icon-wechat-pay-fill" />
              微信支付
            </div>
          </div>
          <div v-if="tabActive == 1" class="QRCode-box" >
            <div class="QRCode" ref="QRCode"></div>
          </div>
        </div>
      </div>
      <div v-if="active == 2" class="success-box">
        <div class="icon"><i class="iconfont zgyf-icon-yiwancheng" /></div>
        <div class="h">订购成功</div>
        <div class="em">服务商正在抓紧联系中，请稍等</div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import Clipboard from 'clipboard'
import QRCode from 'qrcodejs2'
import { weChatPay, getPaymentState, completePayment, weChatPayByService, getServicePaymentState } from '@/api/vip/order'
import { getInfo } from '@/api/asso/system/associationInfo'

export default {
  components: {
    QRCode
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    tableData: {
      type: Array,
      default: () => []
    },
    active: {
      type: Number,
      default: 0
    },
    orderType: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      checked: false,
      tabActive: 1,
      qrcode: '',
      time: null,
      renewal: {},
      rowData: {},
      companyData: {}
    }
  },
  computed: {
    payAmount() {
    	return function(item,index) {
    		let num = 0
        if (this.active != 0) {
          num = this.rowData.amount
        } else {
          this.tableData.forEach(item => {
            num += item.amount
          })
        }
    		return num
    	}
    }
  },
  watch: {
    tabActive(val) {
      if (val == 2) {
        clearTimeout(this.time)
      }
    }
  },
  destroyed() {
    clearTimeout(this.time)
  },
  methods: {
    createQrcode(url) {
      if(this.qrcode) {  // 有新的二维码地址了，先把之前的清除掉
        this.$refs.QRCode.innerHTML = ''
      }
      this.qrcode = new QRCode(this.$refs.QRCode, {
        text: url, //页面地址 ,如果页面需要参数传递请注意哈希模式#
        width: 120, // 二维码宽度 （不支持100%）
        height: 120, // 二维码高度 （不支持100%）
        // colorDark: this.colorDark,
        // colorLight: this.colorLight,
        correctLevel: QRCode.CorrectLevel.H,
      })
    },
    handleClose() {
      clearTimeout(this.time)
      this.checked = false
      this.$emit('dialogClose')
      this.$emit('update:visible', false)
    },
    payment(data, type) {
      console.log(data)
      if (this.checked || this.active != 0) {
        this.$emit('stepNext', 1)
        this.rowData = data
        if (type === 'members') {
          weChatPay(data.id).then(res => {
            if (res.code == 200) {
              this.createQrcode(res.data)
              this.getDetail(type)
            }
          })
        } else if (type === 'service') {
          weChatPayByService(data.id).then(res => {
            if (res.code == 200) {
              this.createQrcode(res.data)
              this.getDetail(type)
            }
          })
        }
      } else {
        this.$message({
          message: '请阅读并同意《支付服务协议》',
          type: 'error',
          duration: 1000
        })
      }
    },
    getDetail(type) {
      const id = this.tableData.length > 0 && this.tableData[0].id ? this.tableData[0].id : this.rowData.id
      this.time = setTimeout(() => {
        if (type === 'members') {
          getPaymentState(id).then(res => {
            if (res.code == 200) {
              if (res.data.paymentState == 1) {
                clearTimeout(this.time)
                this.renewal = res.data
                this.$emit('stepNext', 2)
              } else if (res.data.paymentState == 0) {
                clearTimeout(this.time)
                this.getDetail(type)
              }
            }
          })
        } else if (type === 'service') {
          getServicePaymentState(id).then(res => {
            if (res.code == 200) {
              if (res.data.paymentState == 1) {
                clearTimeout(this.time)
                this.$emit('stepNext', 2)
              } else if (res.data.paymentState == 0) {
                clearTimeout(this.time)
                this.getDetail(type)
              }
            }
          })
        }
      }, 1000)
    },
    tabClick(val) {
      console.log(val)
      if (val === 1) {
        clearTimeout(this.time)
        weChatPay(this.rowData.id).then(res => {
          if (res.code == 200) {
            this.createQrcode(res.data)
            this.getDetail(this.orderType)
          }
        })
      } else {
        clearTimeout(this.time)
        this.$refs.QRCode.innerHTML = ''
        getInfo().then(res => {
          if (res.code === 200) {
            this.companyData = res.data
          }
        })
      }
      this.tabActive = val
    },
    copy() {
      var clipboard = new Clipboard('.copyBtn')
      clipboard.on('success', e => {
        this.$message.success('已成功复制到粘贴板')
        //  释放内存
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        // 不支持复制
        this.$message.warning('该浏览器不支持复制')
        // 释放内存
        clipboard.destroy()
      })
    },
    goToLink(url) {
      console.log(url)
      if (this.$route.path === url) {
        this.handleClose()
      } else {
        this.$router.push(url)
      }
    },
    successPay() {
      this.$confirm('点击「确认」按钮后，将无法撤销操作。稍后，协会客服会尽快为您确认到账。', '是否确定已经完成对公支付？', {
        type: 'warning'
      }).then(() => {
        completePayment(this.rowData.id).then(res => {
          if (res.code === 200) {
            this.handleClose()
          }
        })
      }).catch(() => {
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-dialog {
  .box {
    .order-box {
      .el-table {
        margin: 2rem 0 2.5rem 0;
        ::v-deep .el-table__header {
          thead th {
            background: #f2f3f5;
            padding: 4px 0;
          }
        }
      }
      .payment {
        text-align: right;
        font-size: 0.875rem;
        line-height: 1.375rem;
        span {
          font-size: 0.875rem;
          line-height: 1.375rem;
          color: #F53F3F;
        }
      }
      .btns {
        margin-top: 1.75rem;
        text-align: right;
        .btn {
          display: inline-block;
          font-size: 1rem;
          line-height: 1.5rem;
          padding: 0.25rem 1.25rem;
          border-radius: 0.25rem;
          color: #FFFFFF;
          background: #F53F3F;
          cursor: pointer;
        }
      }
      .agreement {
        text-align: right;
        margin-top: 0.5rem;
        .link {
          color: #165DFF;
        }
      }
    }
    .payment-box {
      padding-top: 3.25rem;
      text-align: center;
      .h {
        font-size: 1rem;
        line-height: 1.5rem;
        margin-bottom: 0.8125rem;
      }
      .em {
        font-size: 0.875rem;
        line-height: 1.375rem;
        color: #86909c;
        margin-bottom: 0.5rem;
      }
      .price {
        font-size: 0.875rem;
        line-height: 1.375rem;
        margin-bottom: 2.25rem;
        span {
          font-size: 0.875rem;
          line-height: 1.375rem;
          color: #F53F3F;
        }
      }
      .pay-tab{
        .tab{
          display: flex;
          align-items: center;
          justify-content: center;
          margin-bottom: 1.25rem;
          .box{
            display: flex;
            align-items: center;
            justify-content: center;
            width: 10rem;
            height: 2rem;
            line-height: 2rem;
            font-size: 1rem;
            text-align: center;
            background: #FFFFFF;
            border: 1px solid #e5e6eb;
            color: #86909c;
            cursor: pointer;
            border-top-left-radius: .25rem;
            border-bottom-left-radius: .25rem;
            border-bottom-right-radius: 0;
            border-bottom-right-radius: 0;
            &.active{
              background: #00B42A;
              border: 1px solid #00B42A;
              color: #FFFFFF;
            }
            .iconfont{
              font-size: 1.5rem;
              margin-right: 0.25rem;
            }
          }
          .box ~ .box{
            border-top-left-radius: 0;
            border-bottom-left-radius: 0;
            border-bottom-right-radius: .25rem;
            border-bottom-right-radius: .25rem;
          }
        }
        .QRCode-box{
          text-align: center;
          .QRCode{
            display: inline-block;
          }
        }
        .company-pay{
          display: flex;
          padding: 0 3.125rem;
          text-align: left;
          .tips{
            color: #f00;
          }
          .step1{
            width: 50%;
          }
          .step2{
            width: 50%;
            .footer{
              margin-top: 1.25rem;
            }
          }
        }
      }
    }
    .success-box{
      padding-top: 3.25rem;
      text-align: center;
      .icon{
        margin-bottom: 1.5rem;
        color: #00B42A;
        .iconfont{
          font-size: 3rem;
        }
      }
      .h {
        font-size: 1rem;
        line-height: 1.5rem;
        margin-bottom: 0.8125rem;
      }
      .em {
        font-size: 0.875rem;
        line-height: 1.375rem;
        color: #86909c;
        margin-bottom: 2.25rem;
      }
      .btns{
        text-align: center;
        padding-bottom: 3.75rem;
        .btn{
          display: inline-block;
          font-size: 1rem;
          line-height: 1.5rem;
          padding: 0.25rem 1.25rem;
          color: #165DFF;
          background: #E8F3FF;
          border: 1px solid #165DFF;
          border-radius: 0.25rem;
        }
      }
    }
  }
}
</style>
